package com.sojson.project.sys.user.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sojson.config.exception.TransErrorCode;
import com.sojson.enums.EEnvironmentUserType;
import com.sojson.enums.core.ELoginDeviceType;
import com.sojson.enums.core.ERoleType;
import com.sojson.project.sys.role.entity.dto.RoleDto;
import com.sojson.project.sys.role.entity.vo.RoleVo;
import com.sojson.project.sys.role.service.RoleService;
import com.sojson.project.sys.user.controller.param.verify.UserMerchantParamVerify;
import com.sojson.project.sys.user.entity.dto.UserMerchantDto;
import com.sojson.project.sys.user.entity.dto.UserMerchantPageDto;
import com.sojson.project.sys.user.entity.po.UserMerchant;
import com.sojson.project.sys.user.entity.vo.UserMerchantVo;
import com.sojson.project.sys.user.service.UserMerchantService;
import com.sojson.result.Result;
import com.sojson.util.enums.ELoginOtherType;
import com.sojson.util.poi.ExcelUtil;
import com.sojson.util.token.TokenDto;
import com.sojson.util.token.TokenUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 商户表控制器
 * 
 * @author liu
 * @date 2022-12-05
 */
@Api(tags = "商户表管理")
@RestController
@RequestMapping("/sys/user/merchant")
public class UserMerchantController {

    @Autowired
    private UserMerchantService userMerchantService;
    @Autowired
    private RoleService roleService;

    /**
     * 帐号密码注册
     * 
     * @param dto
     * @return
     * @throws Exception 
     */
    @PostMapping("/pwdRegister")
    @PreAuthorize("@ss.hasPermi('/sys/user/merchant/pwdRegister')")
    @ApiOperation("管理员密码注册")
    public Result<Boolean> pwdRegister(@RequestBody TokenDto dto) throws Exception {
        // 校验参数
        Result<Boolean> paramResult = UserMerchantParamVerify.pwdRegister(dto);
        // 验证不通过
        if (!paramResult.getCode().equals(TransErrorCode.SUCCESS.getCode())) {
            return paramResult;
        }

        return Result.success(userMerchantService.pwdRegister(dto));
    }

    /**
     * 密码登录
     * 
     * @param dto
     * @return
     * @throws Exception 
     */
    @PostMapping("/pwdLogin")
    @ApiOperation("管理员密码登录")
    public Result<String> pwdLogin(@RequestBody TokenDto dto) throws Exception {
        // 校验参数
        Result<String> paramResult = UserMerchantParamVerify.pwdLogin(dto);
        // 验证不通过
        if (!paramResult.getCode().equals(TransErrorCode.SUCCESS.getCode())) {
            return paramResult;
        }

        // 参数初始化
        dto.setLoginEnv(EEnvironmentUserType.WEB_MERCHANT.getCode());
        dto.setLoginType(ELoginOtherType.GENERAL.getCode());
        dto.setTypeLoginDevice(ELoginDeviceType.COMPUTER.getCode());
        userMerchantService.pwdLogin(dto);
        // 返回结果
        return Result.success(TokenUtil.getClaimsStr());
    }

    /**
     * 通过id更新
     * 
     * @param dto
     * @return
     * @throws IOException 
     */
    @PutMapping("/updateById")
    @PreAuthorize("@ss.hasPermi('/sys/user/merchant/updateById')")
    @ApiOperation("通过id更新管理员用户表数据")
    public Result<Boolean> updateById(@RequestBody UserMerchantDto dto) throws IOException {
        // 校验参数
        Result<Boolean> paramResult = UserMerchantParamVerify.updateById(dto);
        // 验证不通过
        if (!paramResult.getCode().equals(TransErrorCode.SUCCESS.getCode())) {
            return paramResult;
        }
        // 权限校验
        List<String> userIds = new ArrayList<>();
        userIds.add(dto.getId());
        userMerchantService.isPerm(userIds);

        // 修改信息
        userMerchantService.update(dto);
        return Result.success();
    }

    /**
     * 列表查询
     * 
     * @param dto
     * @return
     */
    @GetMapping("/list")
    @PreAuthorize("@ss.hasPermi('/sys/user/merchant/list')")
    @ApiOperation(value = "查询管理员用户表数据", response = UserMerchantVo.class)
    public Result<List<UserMerchantVo>> list(UserMerchantDto dto) {
        return Result.success(userMerchantService.list(dto));
    }

    /**
     * 分页查询
     * 
     * @param dto
     * @return
     */
    @GetMapping("/page")
    @PreAuthorize("@ss.hasPermi('/sys/user/merchant/page')")
    @ApiOperation(value = "分页查询管理员用户表数据", response = UserMerchantVo.class)
    public Result<List<UserMerchantVo>> page(UserMerchantPageDto dto) {
        return Result.success(userMerchantService.page(dto));
    }

    /**
     * 导出数据
     * 
     * @param dto
     * @return
     * @throws Exception 
     */
    @GetMapping("/export")
    @PreAuthorize("@ss.hasPermi('/sys/user/merchant/export')")
    @ApiOperation("导出管理员用户表数据")
    public void export(UserMerchantDto dto) throws Exception {
        List<UserMerchantVo> list = userMerchantService.list(dto);
        ExcelUtil<UserMerchantVo> excelUtil = new ExcelUtil<>(UserMerchantVo.class);
        excelUtil.exportExcelOutFile(list, "管理员用户表");
    }

    /**
     * 通过id查询
     * 
     * @param id
     * @return
     * @throws IOException 
     */
    @GetMapping("/info/{id}")
    @PreAuthorize("@ss.hasPermi('/sys/user/merchant/info/{id}')")
    @ApiOperation(value = "通过id查询管理员用户表数据", response = UserMerchantVo.class)
    public Result<UserMerchantVo> info(@PathVariable String id) throws IOException {
        Result<UserMerchantVo> success = Result.success();

        // 获取当前用户的角色ID列表
        Set<String> roleIds = roleService.getRoleIdsByUserId(id);
        // 获取所有角色
        List<RoleVo> list = roleService.list(new RoleDto());
        // 所有角色的ID
        List<String> listIds = list.stream().map(RoleVo::getId).collect(Collectors.toList());

        // 将没有权限的角色去掉
        Iterator<String> iterator = roleIds.iterator();
        while (iterator.hasNext()) {
            String roleId = iterator.next();
            if (listIds.contains(roleId)) {
                continue;
            }
            iterator.remove();
        }
        success.put("roles", list);
        // 超级管理员Key
        success.put("adminSuperKey", ERoleType.ADMIN_SUPER.getKey());

        // 权限校验
        if ("0".equals(id)) {
            return success;
        }

        List<String> userIds = new ArrayList<>();
        userIds.add(id);
        userMerchantService.isPerm(userIds);

        UserMerchantVo findById = userMerchantService.findById(id);
        if (findById == null) {
            return success;
        }
        // 获取用户
        success.setData(findById);
        success.put("roleIds", roleIds);
        return success;
    }

    /**
     * 通过id列表删除
     * 
     * @param dto
     * @return
     * @throws IOException 
     */
    @DeleteMapping("/remove")
    @PreAuthorize("@ss.hasPermi('/sys/user/merchant/remove')")
    @ApiOperation("通过id列表删除管理员用户表数据")
    public Result<Boolean> remove(@RequestBody UserMerchantDto dto) throws IOException {
        List<String> ids = dto.getIds();
        if (ids == null || ids.size() == 0) {
            return Result.success();
        }

        // 权限校验
        userMerchantService.isPerm(ids);

        userMerchantService.removeByIds(ids);
        return Result.success();
    }

    /**
     * 密码重置
     * 
     * @param dto
     * @return
     * @throws Exception 
     */
    @PutMapping(value = "/resetUserPwd")
    @PreAuthorize("@ss.hasPermi('/sys/user/merchant/resetUserPwd')")
    @ApiOperation("密码重置")
    public Result<Boolean> resetUserPwd(@RequestBody UserMerchant dto) throws Exception {
        // 校验参数
        Result<Boolean> paramResult = UserMerchantParamVerify.resetUserPwd(dto);
        // 验证不通过
        if (!paramResult.getCode().equals(TransErrorCode.SUCCESS.getCode())) {
            return paramResult;
        }

        // 权限校验
        List<String> userIds = new ArrayList<>();
        userIds.add(dto.getId());
        userMerchantService.isPerm(userIds);

        UserMerchant u = new UserMerchant();
        u.setId(dto.getId());
        u.setPwd(dto.getPwd());
        // 修改密码
        return Result.success(userMerchantService.resetUserPwd(u));
    }

    /**
     * 通过id修改状态
     * 
     * @param dto
     * @return
     * @throws Exception 
     */
    @PutMapping("/updateStatus")
    @PreAuthorize("@ss.hasPermi('/sys/user/merchant/changeStatus')")
    @ApiOperation("通过id修改用户状态")
    public Result<Boolean> updateStatus(@RequestBody UserMerchant dto) throws Exception {
        // 校验参数
        Result<Boolean> paramResult = UserMerchantParamVerify.updateStatus(dto);
        // 验证不通过
        if (!paramResult.getCode().equals(TransErrorCode.SUCCESS.getCode())) {
            return paramResult;
        }

        // 权限校验
        List<String> userIds = new ArrayList<>();
        userIds.add(dto.getId());
        userMerchantService.isPerm(userIds);

        // 修改状态
        UserMerchant user = new UserMerchant();
        user.setId(dto.getId());
        user.setStatus(dto.getStatus());
        userMerchantService.updateStatus(user);
        return Result.success();
    }

}